<!DOCTYPE html>
<html>

<head>
    <title>
        chatRoom
    </title>
    <script src="/socket.io/socket.io.js" charset="utf-8"></script>
    <link rel='stylesheet' href='/stylesheets/style.css' />
</head>

<body>
    <%if(user==undefined){%>
        <p>
            <a href="/login">登陆</a> | <a href="/reg">注册</a>
        </p>
    <%}else{%>
        <p>
            <a href="/logout">退出</a>
        </p>
    <%}%>
    <div class="chatSection">
        <%if(user){%>
            <h2 class="yhm">欢迎&nbsp;“<span><%=user.username%></span>”&nbsp;光临本聊天室</h2>
        <%}%>

    </div>
    <%if(user){%>
        <div class="sendBox">
            <input type="text" name="sendCon">
            <button type="button" class="sendBtn">发送</button>
        </div>
    <%}%>

    <script type="text/javascript">

        function getSay(){
            return document.querySelector('input[name=sendCon]').value || 'no';
        }
        function addPEle(data,username){
            // chatSection
            var chatSection = document.querySelector('.chatSection');
            var pTimeEle = document.createElement('p');
            pTimeEle.innerHTML = data.time;
            pTimeEle.className = 'textCenter';

            chatSection.appendChild(pTimeEle);

            var pEle = document.createElement('p');
            var spanEle = document.createElement('span');
            var iEle = document.createElement('i');
            if(data.username==username){
                pEle.appendChild(iEle);
                pEle.appendChild(spanEle);
                pEle.className ='m';
                spanEle.innerHTML = '&nbsp;&lt;&nbsp;'+data.username;
            }else{
                pEle.appendChild(spanEle);
                pEle.appendChild(iEle);
                spanEle.innerHTML = data.username+'&nbsp;&gt;&nbsp;';
            }
            iEle.innerText = data.msg;
            chatSection.appendChild(pEle);
        }
        var socket = io();
        io.connect();
        socket.on('newSay',function(data){
            var username = document.querySelector('.yhm span').innerText;
            addPEle(data,username);
        });
        var sendBtn = document.querySelector('.sendBtn');
        if(sendBtn){
            sendBtn.addEventListener('click',function(){
                var username = document.querySelector('.yhm span').innerText;
                socket.emit('say',{username:username,msg:getSay()});
            });
        }
    </script>
</body>

</html>
